package leetcode.Y2024M6.study;

import leetcode.Y2024M6.TreeNode;
import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

public class S117 {
    public TreeNode connect(TreeNode root) {
        if (root == null) return null;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            TreeNode[] arr = new TreeNode[queue.size()];
            int index = 0;
            for (TreeNode node : queue) {
                arr[index++] = node;
            }
            for (int i = 0; i < arr.length-1; i++) {
                arr[i].next=arr[i+1];
            }
        }
        return root;

    }

    @Test
    public void test() {
        int[] root = {1, 2, 3, 4, 5, -1, 7};
        TreeNode tree = TreeNode.createTree(root);
        connect(tree);
    }
}
